package c.x.jy.service.utils.mqtt;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.PostConstruct;

import c.x.jy.common.utils.DateUtils;
import c.x.jy.dao.entity.OrderAwnserEntity;
import c.x.jy.service.service.OrderAwnserService;
import c.x.jy.service.utils.SpringContextUtils;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;

import c.x.jy.common.rabbitMQ.RabbitMqConstant;
import c.x.jy.service.redis.Cache;
import lombok.extern.slf4j.Slf4j;

 @Slf4j
public class OutPaperBackMsg {
  
 
	public OutPaperBackMsg(Cache redisUtils ){
		this.redisUtils=redisUtils;

	}
	

	private Cache redisUtils;


	// private OrderAwnserService orderAwnserService;

 
	protected static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

//{"nickname":"🐱 🐱 😈","image":"https://thirdwx.qlogo.cn/mmopen/vi_32
// /C57HgfenFwWnqFD7HABoYVP561mPuw1kO2dJ7n493SQajooibMyL50uoiczYxAG9Y785bHEIl2iadndzLjRjWkMJA/132",
// "date":"2021-06-13","stime":"22:06:19","content":"adsf","memberId":3}
	 //{"nickname":"🐱 🐱 😈","image":"https://thirdwx.qlogo.cn/mmopen/vi_32/C57HgfenFwWnqFD7HABoYVP561mPuw1kO2dJ7n493SQajooibMyL50uoiczYxAG9Y785bHEIl2iadndzLjRjWkMJA/132",
// "date":"2021-06-13","stime":"23:41:24","content":"sdfd","memberId":3,"groupName":"1_3"}

	 //0 初使化，更新新消息
	public void getbackdata(String message) {
		JSONObject json = new JSONObject();
		message = message.replaceAll("&amp;", "&");
		message = message.replaceAll("�", "");
		message = message.replaceAll("\r", "");
		message = message.replaceAll("\n", "").trim();
		json = (JSONObject) json.parse(message);

		log.info("message:{}", message);
		
		switch(json.getInteger("code") ){
		case 0 :
       try {


		log.info("初使化");
			JSONObject data=json.getJSONObject("data");
			QueryWrapper<OrderAwnserEntity> query=new QueryWrapper<OrderAwnserEntity>();

		    query.lambda().eq(OrderAwnserEntity::getTeacherId,Long.valueOf(data.getString("groupName").split("_")[0]))
				   .eq(OrderAwnserEntity::getMemberId,Long.valueOf(data.getString("groupName").split("_")[1]))
				   .eq(OrderAwnserEntity::getStartDate,data.getDate("date"));
			OrderAwnserEntity entity=SpringContextUtils.getBean(OrderAwnserService.class).selectOne(query);
		//	orderAwnserService.selectByIdForUpdate(entity.getId());
			log.info(JSON.toJSONString(entity));
			if(entity==null) {
				JSONObject group =new JSONObject();
				JSONArray jsonArray=new JSONArray();
				jsonArray.add(json.getJSONObject("chats"));
				group.put("chats", jsonArray);
				group.put("memberId",data.getLongValue("memberId"));
				group.put("date",data.getString("date"));
				group.put("image",data.getString("image"));
				group.put("nickname",data.getString("nickname"));
				entity = new OrderAwnserEntity();
				entity.setBusinessType(0);
				entity.setStartDate(data.getDate("date"));
				entity.setEndDate(data.getDate("date"));
				entity.setContent(group.toJSONString());
				entity.setMemberId(Long.valueOf(data.getString("groupName").split("_")[1]));//memberId groupName
				entity.setTeacherId(Long.valueOf(data.getString("groupName").split("_")[0]));
				if (json.getLong("orderId") != null) {
					entity.setOrderId(json.getLong("orderId"));
				}
				entity.setStatus(0);
				entity.setNewPoint(data.getString("stime"));
				SpringContextUtils.getBean(OrderAwnserService.class).save(entity);
			}else{
				JSONObject object=	JSONObject.parseObject(entity.getContent());
				JSONArray array=	 object.getJSONArray("chats");
				if(array.size()>0&& DateUtils.compareTime(json.getJSONObject("chats").getString("stime"), array.getJSONObject(array.size()-1).getString("stime"))==0)
					return;
				array.add(json.getJSONObject("chats"));
				entity.setContent(object.toJSONString());
				if(entity.getStatus().equals(1)){
					entity.setNewPoint(data.getString("stime"));
					entity.setStatus(0);
				}
				SpringContextUtils.getBean(OrderAwnserService.class).updateById(entity);
			}

	   }catch (Exception e){
           e.printStackTrace();
	   }

 
		break;
      //  获取未读信息
		case 2 :
		try {
			JSONObject data=json.getJSONObject("data");
			QueryWrapper<OrderAwnserEntity> query=new QueryWrapper<OrderAwnserEntity>();
			//query.lambda().eq(OrderAwnserEntity::getTeacherId,Long.valueOf(data.getString("groupName").split("_")[0]))
			query.lambda().eq(OrderAwnserEntity::getTeacherId,data.getLongValue("memberId"))
					.eq(OrderAwnserEntity::getStatus,0);
			if(data.containsKey("date"))	query.lambda().eq(OrderAwnserEntity::getStartDate,data.getDate("date"));
			List<OrderAwnserEntity > list=	SpringContextUtils.getBean(OrderAwnserService.class).getBaseMapper().selectList(query);
			JSONArray array=new JSONArray();
			JSONObject group=new JSONObject();
			for (OrderAwnserEntity orderAwnserEntity: list ) {
				OrderAwnserEntity newo=new OrderAwnserEntity();
				newo.setStatus(1);
				newo.setId(orderAwnserEntity.getId());
				//orderAwnserEntity.setNewPoint("0");
				SpringContextUtils.getBean(OrderAwnserService.class).updateById(newo);
				JSONObject object=	JSONObject.parseObject(orderAwnserEntity.getContent());
				//JSONArray array=	 object.getJSONArray("chats");
				//array.addAll(object.getJSONArray("chats"));
				object.getJSONArray("chats").stream().iterator().forEachRemaining((o)->{
					JSONObject  obj= (JSONObject) o;
					//obj.getString("stime");
					if(DateUtils.compareTime(obj.getString("stime"),orderAwnserEntity.getNewPoint())>=0){
						array.add(o);
					}
				});
				group.put("memberId",object.getLongValue("memberId"));
				group.put("date",object.getString("date"));
				group.put("image",object.getString("image"));
				group.put("nickname",object.getString("nickname"));
			}
			group.put("chats",array );
			group.put("code",3 );
			MqttMessage mqttMessage = new MqttMessage(group.toJSONString().getBytes());
			mqttMessage.setQos(1);
		    SpringContextUtils.getBean(MqttClient.class).publish(data.getString("from"),mqttMessage) ;
			} catch ( Exception e) {

				e.printStackTrace();
			}

		break;
		case 4 :
			//更新信息状态 已读
			try{
				JSONObject data=json.getJSONObject("data");
				QueryWrapper<OrderAwnserEntity> query=new QueryWrapper<OrderAwnserEntity>();
				query.lambda().eq(OrderAwnserEntity::getTeacherId,Long.valueOf(data.getString("groupName").split("_")[0]))
						.eq(OrderAwnserEntity::getMemberId,Long.valueOf(data.getString("groupName").split("_")[1]))
						.eq(OrderAwnserEntity::getStartDate ,data.getDate("date"));
				OrderAwnserEntity entity=	SpringContextUtils.getBean(OrderAwnserService.class).getBaseMapper().selectOne(query);
				OrderAwnserEntity newo=new OrderAwnserEntity();
				newo.setStatus(1);
				newo.setId(entity.getId());
				SpringContextUtils.getBean(OrderAwnserService.class).updateById(newo);
			}catch (Exception e){

			}


		 	break;
		case 6:
			//订单 查询

			
			break;
		default :
	 
		break;
		}
		


	 
	}



}
